<template>
  <div>
    <div class="bottom-container">
      <van-nav-bar title="配送站注册" />
      <upload-pic @iconChange="iconChange" :showIcon="form.icon"></upload-pic>
      <div class="register-tip" v-show="this.form.icon == ''">请选择图片~</div>
      <van-cell-group>
        <van-field v-model="form.stationName" label="配送站名称" clearable v-validate="'required|special'"
          data-vv-name="配送站名称" :error-message="errors.first('配送站名称')" placeholder="请输入配送站名称" required maxLength="20" />
        <van-field v-model="form.stationContact" label="联系方式" clearable v-validate="'required|mobile'"
          data-vv-name="联系方式" :error-message="errors.first('联系方式')" placeholder="请输入配送站联系方式" required maxLength="20" />
        <van-field v-model="sms" center clearable label="短信验证码" placeholder="请输入短信验证码" required v-validate="'required'"
          data-vv-name="短信验证码" :error-message="errors.first('短信验证码')" maxLength="4">
          <van-button slot="button" size="small" type="primary" :disabled="canSend" @click="sendSmsCode()">
            {{sendBtnText}}</van-button>
        </van-field>
        <van-field v-model="form.userName" label="负责人名称" clearable v-validate="'required'" data-vv-name="负责人名称"
          :error-message="errors.first('负责人名称')" placeholder="请输入负责人名称" required maxLength="20" />
        <van-field v-model="form.userContact" label="联系方式" clearable v-validate="'required|mobile'"
          data-vv-name="负责人联系方式" :error-message="errors.first('负责人联系方式')" placeholder="请输入负责人联系方式" required
          maxLength="20" />

        <van-field v-model="form.region" @focus="focusCity" label="所在城市" v-validate="'required'" data-vv-name="所在城市"
          :error-message="errors.first('所在城市')" readonly placeholder="请选择所在城市" required />
        <van-field v-model="form.address" label="详细地址" clearable v-validate="'required'" data-vv-name="详细地址"
          :error-message="errors.first('详细地址')" type="textarea" placeholder="请输入详细地址" required maxLength="80" />
        <div class="get-location">
          <van-button slot="right-icon" size="small" type="primary" @click="getLocation()">获取当前地址</van-button>
        </div>
        <van-field v-model="form.openTime" @focus="focusStart" label="营业开始时间" readonly v-validate="'required'"
          data-vv-name="营业开始时间" :error-message="errors.first('营业开始时间')" placeholder="" required />
        <van-field v-model="form.closeTime" @focus="focusEnd" label="营业结束时间" readonly v-validate="'required'"
          data-vv-name="营业结束时间" :error-message="errors.first('营业结束时间')" placeholder="" required />
        <van-field v-model="form.businessRemarks" label="营业备注" clearable v-validate="'required'" data-vv-name="营业备注"
          :error-message="errors.first('营业备注')" type="textarea" placeholder="请输入营业备注（150字以内）" required
          maxLength="150" />
        <van-field v-model="form.description" label="简介" clearable v-validate="'required'" data-vv-name="简介"
          v-on:focus="focusAAA" :error-message="errors.first('简介')" type="textarea" placeholder="请输入配送站简介（150字以内）"
          required maxLength="150" />
      </van-cell-group>
      <van-popup v-model="popupShow" position="bottom">
        <van-area :area-list="areaList" @cancel="onCancel" @confirm="onConfirm" />
      </van-popup>
      <van-popup v-model="startShow" position="bottom">
        <van-datetime-picker @confirm="startConfirm" @cancel="startCancel" v-model="startTime" type="time" />
      </van-popup>
      <van-popup v-model="endShow" position="bottom">
        <van-datetime-picker @confirm="endConfirm" @cancel="endCancel" v-model="endTime" type="time" />
      </van-popup>
    </div>
    <van-button class="bottom-btn" size="large" @click="register" type="info">保存</van-button>
  </div>
</template>

<script>
  import UploadPic from '@/components/UploadPic'
  import {
    REGISTER_STATION,
    ADDRESS_TO_COORDINATE,
    STATION_CHECK,
    GDMAP_KEY
  } from '@/api/user'
  import {
    sendSms,
    checkSmsCode
  } from '@/api/common'
  import area from '@/util/area'
  import axios from 'axios'
  import {
    setInterval,
    clearInterval
  } from 'timers';
  export default {
    components: {
      UploadPic
    },
    data() {
      return {
        startTime: '',
        endTime: '',
        startShow: false,
        endShow: false,
        form: {
          stationName: '',
          stationContact: '',
          userName: '',
          userContact: '',
          region: '',
          address: '',
          description: '',
          icon: '',
          openTime: '',
          closeTime: '',
          businessRemarks: ''
        },
        canSend: false,
        sendBtnText: '发送验证码',
        sendInterval: null,

        errorMsg: {
          stationName: '',
          stationContact: '',
          userName: '',
          userContact: '',
          region: '',
          address: '',
          description: '',
        },
        sms: '',
        popupShow: false,
        areaList: area,
        rules: {
          stationName: [{
            required: true,
            message: '请输入配送站名称'
          }],
        },
      }
    },
    mounted() {
      debugger
      if (sessionStorage.getItem('lastUploadPic')) {
        this.form.icon = sessionStorage.getItem('lastUploadPic')
      }
      var browser = {
        versions: function () {
          var u = navigator.userAgent,
            app = navigator.appVersion;
          return { //移动终端浏览器版本信息
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile/i) || !!u.match(
              /MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/
            ), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
          };
        }(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
      }
      //如果是安卓focusinput框
      if (browser.versions.android) {
        window.addEventListener("resize", function () {
          if (document.activeElement.tagName == "INPUT" || document.activeElement.tagName == "TEXTAREA") {
            window.setTimeout(function () {
              document.activeElement.scrollIntoViewIfNeeded();
            }, 0);
          }
        })
      }

      //判断注册
      this.$reqGet(STATION_CHECK, {
        openid: sessionStorage.getItem('openid')
      }).then(res => {
        if (res.data.status == 1) {
          this.$router.replace('/order')
        } else if (res.data.status == 2) {
          this.$router.replace('/checking')
        }
      });
    },
    methods: {
        //获取定位
      getLocation() {
        this.$toast('正在获取中')
        AMap.plugin('AMap.Geolocation', () => {
          let geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
          });
          geolocation.getCurrentPosition();
          //定位成功
          AMap.event.addListener(geolocation, 'complete', data => {
            const address = data.addressComponent
            const fullProvince = address.province + address.city + address.district
            this.form.region = address.province + ' ' + address.city + ' ' + address.district
            this.form.address = data.formattedAddress.replace(fullProvince, '')
          });
          //定位失败
          AMap.event.addListener(geolocation, 'error', data => {
            this.$toast('定位失败，请确认您开启定位权限');
          })
        });
      },
      focusStart() {
        this.startShow = true
      },
      focusEnd() {
        this.endShow = true
      },
      startCancel() {
        this.startShow = false
      },
      startConfirm() {
        this.form.openTime = this.startTime
        this.startShow = false
      },
      endCancel() {
        this.endShow = false
      },
      endConfirm() {
        this.form.closeTime = this.endTime
        this.endShow = false
      },
      //选择行政区划
      focusCity() {
        this.popupShow = true;
      },
      //取消选择行政区划
      onCancel() {
        this.popupShow = false;
      },
      //确认选择行政区划
      onConfirm(val) {
        let res = [];
        val.forEach(el => {
          res.push(el.name);
        });
        this.form.region = res.join(' ');
        this.popupShow = false;
      },
      //注册
      register() {
        // if (!this.form.icon) {
        //   this.$toast('请选择图片');
        //   return;
        // }
        this.$validator.validateAll().then((result) => {
          if (result) {
            //校验验证码
            this.$reqGet('https://www.wpengtao.com:8333' + checkSmsCode, {
              phone: this.form.stationContact,
              state: 1,
              codes: this.sms
            }).then(res => {
              if (res.code == '200') {
                if (res.data == 1) {
                  this.saveRegister();
                } else if (res.data == 2) {
                  this.$toast('验证码错误，请输入正确的验证码')
                } else if (res.data == 3) {
                  this.$toast('验证码已失效，请重新发送验证码')
                } else {
                  this.$toast('验证码校验失败')
                }
              } else {
                this.$toast('验证码校验失败')
              }
            }).catch(err => {
              this.$toast('验证码校验失败')
            })
          }
        })
      },
      saveRegister() {
        let params = {
          name: this.form.stationName,
          icon: this.form.icon,
          description: this.form.description,
          phone: this.form.stationContact,
          region: this.form.region,
          address: this.form.address,
          longitude: '',
          latitude: '',
          openid: sessionStorage.getItem('openid'),
          sManager: {
            name: this.form.userName,
            phone: this.form.userContact
          },
          openTime: this.form.openTime,
          closeTime: this.form.closeTime,
          businessRemarks: this.form.businessRemarks
        }
        axios.get(ADDRESS_TO_COORDINATE, {
          params: {
            key: GDMAP_KEY,
            address: params.region + params.address
          }
        }).then(res => {
          //地址解析成坐标
          if (res.status == 200 && res.data.status == '1') {
            let data = res.data.geocodes[0];
            let coordinate = data.location.split(',');
            params.longitude = coordinate[0];
            params.latitude = coordinate[1];
            this.$reqPost(REGISTER_STATION, params).then(res => {
              if (res.data == 1) {
                this.$toast.success('注册成功');
                this.$router.replace('/checking');
              } else {
                this.$toast.fail(res.message);
              }
            });
          }
        });
      },
      //头像改变
      iconChange(val) {
        this.form.icon = val;
      },
      //发送验证码
      sendSmsCode() {
        if (this.form.stationContact == '') {
          this.$toast('请输入配送站联系方式');
          return false;
        }
        if (!(/^((1)\d{10})$/.test(this.form.stationContact))) {
          this.$toast('请输入正确的联系方式');
          return false;
        }
        //倒数60s
        let sec = 60;
        this.canSend = true;
        this.sendBtnText = sec + 's';
        this.sendInterval = setInterval(() => {
          sec--;
          this.sendBtnText = sec + 's';
          if (sec < 0) {
            this.sendBtnText = '发送验证码';
            this.canSend = false;
            clearInterval(this.sendInterval);
          }
        }, 1000);

        this.$reqGet('https://www.wpengtao.com:8333' + sendSms, new URLSearchParams({
          phone: this.form.stationContact,
          state: 1
        })).then(res => {
          console.log(res);
          if (res.code == 200) {
            this.$toast('发送成功');
          } else {
            this.$toast('发送失败，请稍候重试');
          }
        }).catch(err => {
          this.$toast('发送失败，请稍候重试')
          console.log(res);
        });
      },
      focusAAA(e) {

      }
    }
  }

</script>
<style lang="less" scoped>
  .register-tip {
    margin-bottom: 10px;
    text-align: center;
    font-size: 12px;
    color: #999;
  }
  .get-location {
    padding: 10px;
    text-align: right;
  }

</style>
